#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

// tcpclient ip port
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " ip port" << std::endl;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    // 1.创建socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 2.bind，不需要显示完成。第一次 connnet 时，OS会自动完成

    // 3.connet
    int n = ::connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connet error" << std::endl;
    }
    std::cout << "connet " << argv[1] << ":" << argv[2] << " sucess" << std::endl;


    // 建立连接成功，将进行收发数据
    while(1)
    {
        // 发送数据
        std::string msg;
        std::cout << "Please Enter #";
        std::getline(std::cin, msg);
        write(sockfd, msg.c_str(), msg.size());

        // 读取数据
        char in_buffer[1024];
        int n = read(sockfd, in_buffer, sizeof(in_buffer)-1);
        if (n > 0)
        {
            in_buffer[n] = 0;
            std::cout << in_buffer << std::endl;
        }
        else
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }

    ::close(sockfd);
    return 0;
}